package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;


    /*
    *
    * 微信登录
    *
    * */
    @Override
    public User wxlogin(UserLoginDTO userLoginDTO) {
        //分析：
        //调用第三方微信接口获取当前登录用户的openId
        String openid = getOpenid(userLoginDTO.getCode());
        //判断openId是否为空，空表示登录失败，抛出业异常
        if(openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //判断是否为首次登录用户，如果是就将用户信息插入数据库User表中
        User user = userMapper.getByOpenId(openid);
        if(user==null){
            //现将基础信息储存起来，后续用户可以在个人中心修改数据
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }else{//若不是则根据传来的用户

        }


        return user;
    }

    //调用微信接口服务来获取openId
    private String getOpenid(String code) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code", code);
        paramMap.put("grant_type","authorization_code");
        //返回的是Json格式的字符串
        String Json = HttpClientUtil.doGet(WX_LOGIN, paramMap);
        //解析出openId
        JSONObject jsonObject = JSON.parseObject(Json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
